<template>
  <div class="combine-student-container">
    <el-dialog
      title="合并学生"
      v-model="centerDialogVisible"
      width="40%"
      append-to-body
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="tips-select-student">请选择需要合并的学生  <span class="show-select-student-btn" @click="selectStudentDialogVisible = true">选择学生</span></div>
      <div class="select-num">已选择 <span class="num">{{ selectedStudentList.length }}</span></div>
      <el-table
        :data="selectedStudentList"
        border
        max-height="350"
        empty-text="暂无学生"
        :row-style="{height:'20px'}"
        :header-cell-style="{'background-color':'#ededed'}">
        <el-table-column
          align="center"
          header-align="center"
          prop="F_name"
          label="学生姓名"
          show-overflow-tooltip>
        </el-table-column>
        <el-table-column
          align="center"
          header-align="center"
          prop="F_class_name"
          label="班级"
          show-overflow-tooltip>
        </el-table-column>
        <el-table-column
          align="center"
          header-align="center"
          prop="F_account"
          label="学号/考号"
          show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="操作" prop="" align="center" header-align="center" min-width="30px">
          <template #default="scope">
            <span class="btn" @click="deleteStudent(scope.$index, scope.row)">删除</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="tips-txt">
        <i class="el-icon-warning-outline"></i>
        操作提示：
      </div>
      <div class="tips-txt">您正在将以上学生账号<span class="tips-red">删除</span></div>
      <div class="tips-txt">并将其账号下的<span class="tips-red">所有考试数据</span>合并保留至<span class="tips-blue">【{{ student.F_name }}】</span>学生账号下。</div>
      <div class="tips-txt">合并成功后请前往考试重新发布成绩。台并后数据无法复原，请谨慎操作！</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCombine">合并</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      title="选择学生"
      v-model="selectStudentDialogVisible"
      width="50%"
      center
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="selectStudent"
    >
      <div class="select-student-container">
        <div class="unselect-student-container">
          <span class="name">学生列表</span>
          <div class="box">
            <div class="filter-box">
              <el-select size="mini" v-model="selectedGradeId" placeholder="请选择" @change="changeGrade">
                <el-option
                  v-for="item in gradeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
              <el-select size="mini" v-model="selectedClassId" placeholder="请选择" @change="changeClass">
                <el-option
                  v-for="item in classList"
                  :key="item.F_class_id"
                  :label="item.F_class_name"
                  :value="item.F_class_id">
                </el-option>
              </el-select>
              <el-input
                placeholder="请输入姓名或考号搜索..."
                size="mini"
                prefix-icon="el-icon-search"
                v-model="searchValue"
                @change="changSearchValue">
              </el-input>
            </div>
            <el-table
              :data="leftStudentList"
              border
              height="350"
              empty-text="暂无学生"
              highlight-selection-row
              :row-style="{height:'20px'}"
              :row-class-name="rowClassName"
              :header-cell-style="{'background-color':'#ededed'}"
              @selection-change="handleSelectionChange">
              <el-table-column
                type="selection"
                width="35">
              </el-table-column>
              <el-table-column
                align="center"
                header-align="center"
                prop="F_name"
                label="学生姓名"
                show-overflow-tooltip>
              </el-table-column>
              <el-table-column
                align="center"
                header-align="center"
                prop="F_class_name"
                label="班级"
                show-overflow-tooltip>
              </el-table-column>
              <el-table-column
                align="center"
                header-align="center"
                prop="F_account"
                label="学号/考号"
                show-overflow-tooltip>
              </el-table-column>
            </el-table>
            <el-pagination
              small
              background
              layout="prev, pager, next"
              v-model:current-page="page"
              :total="studentTotal"
              @current-change="changePage">
            </el-pagination>
          </div>
        </div>
        <!-- <div class="exchange-select-status">
          <div :class="['to-selected', toRight ? 'selected-status' : '']" @click="handleSelectStatus('right')">
            <i class="el-icon-arrow-right"></i>
          </div>
          <div :class="['to-unselect', !toRight ? 'selected-status' : '']"  @click="handleSelectStatus('left')">
            <i class="el-icon-arrow-left"></i>
          </div>
        </div> -->
        <div class="selected-student-container">
          <div class="selected-tips">已选学生<span class="tips-blue">{{ rightStudentList.length }}</span></div>
          <div class="box">
            <el-table
              :data="rightStudentList"
              border
              height="350"
              empty-text="暂无学生"
              highlight-selection-row
              :row-style="{height:'20px'}"
              :row-class-name="rightRowClassName"
              :header-cell-style="{'background-color':'#ededed'}"
              @selection-change="handleRightSelectionChange">
              <el-table-column
                type="selection"
                width="35">
              </el-table-column>
              <el-table-column
                align="center"
                header-align="center"
                prop="F_name"
                label="学生姓名"
                show-overflow-tooltip>
              </el-table-column>
              <el-table-column
                align="center"
                header-align="center"
                prop="F_class_name"
                label="班级"
                show-overflow-tooltip>
              </el-table-column>
              <el-table-column
                align="center"
                header-align="center"
                prop="F_account"
                label="学号/考号"
                show-overflow-tooltip>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="selectStudent(0)">取消</el-button>
          <el-button type="primary" @click="selectStudent(1)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  props: {
    student: Object,
    gradeAndClass: Object,
  },
  data () {
    return {
      centerDialogVisible: true,
      selectStudentDialogVisible: false,
      selectedGradeId: 0,
      selectedClassId: '',
      searchValue: '',
      leftStudentList: [], // 左侧所有学生的列表
      rightStudentList: [], // 右侧所有学生的列表
      page: 1,
      studentTotal: 0,
      leftSelectAccount: [], // 左侧被选中的学生考号列表
      rightSelectAccount: [], // 右侧被选中的学生考号列表
      toRight: true,
      selectedStudentList: [], // 选中的学生列表
    }
  },
  computed: {
    ...mapGetters('school', ['schoolId']),
    gradeList() {
      const list = []
      Object.keys(this.gradeAndClass).forEach(i => {
        const res = this.$maps.gradeList.find((e) => e.id === Number(i))
        if (res) list.push(res)
      })
      list.unshift({ id: 0, name: '全部' })
      return list
    },
    classList() {
      const list = []
      if (this.selectedGradeId !== 0) {
        list.push(...this.gradeAndClass[this.selectedGradeId])
      }
      list.unshift({ F_class_id: '', F_class_name: '全部' })
      return list
    }
  },
  watch: {
    centerDialogVisible (val) {
      if (!val) {
        this.$emit('closeCombineStudent')
      }
    },
  },
  created() {
    this.getStudent()
  },
  methods: {
    async getStudent() {
      const res = await this.$api.getStudents({
        F_grade: this.selectedGradeId,
        F_class_id: this.selectedClassId,
        F_name: this.searchValue,
        F_gender: 0,
        F_page: this.page,
        F_limit: 10,
        F_school_id: this.schoolId,
      })
      this.leftStudentList = res.F_students.filter(e => e.F_id !== this.student.F_id) || []
      if (this.leftStudentList.length === res.F_students.length) {
        this.studentTotal = res.F_total
      } else {
        this.studentTotal = res.F_total - 1
      }
      this.leftStudentList.sort((a, b) => Number(a.F_grade) - Number(b.F_grade))
    },
    changeGrade(val) {
      this.selectedGradeId = val
      this.selectedClassId = ''
      this.searchValue = ''
      this.page = 1
      this.getStudent()
    },
    changeClass(val) {
      this.selectedClassId = val
      this.searchValue = ''
      this.page = 1
      this.getStudent()
    },
    handleSelectionChange(val) {
      this.leftSelectAccount = val.map(e => e.F_account)
      this.handleSelectStatus('right')
    },
    rowClassName({ row }) {
      if (this.leftSelectAccount.includes(row.F_account)) {
        return 'blue-row'
      }
    },
    handleRightSelectionChange(val) {
      this.rightSelectAccount = val.map(e => e.F_account)
      this.handleSelectStatus('left')
    },
    rightRowClassName({ row }) {
      if (this.rightSelectAccount.includes(row.F_account)) {
        return 'blue-row'
      }
    },
    changePage() {
      this.getStudent()
    },
    changSearchValue() {
      this.getStudent()
    },
    handleSelectStatus(type) {
      this.toRight = type === 'right'
      if (type === 'right' && this.leftSelectAccount.length > 0) {
        const leftList = JSON.parse(JSON.stringify(this.leftStudentList))
        this.leftStudentList = leftList.filter(e => !this.leftSelectAccount.includes(e.F_account))
        const rightList = leftList.filter(e => this.leftSelectAccount.includes(e.F_account))
        rightList.forEach(e => {
          if (!this.rightStudentList.find(i => i.F_account === e.F_account)) {
            this.rightStudentList.push(e)
          }
        })
      } else if (type === 'left' && this.rightSelectAccount.length > 0) {
        const rightList = JSON.parse(JSON.stringify(this.rightStudentList))
        this.rightStudentList = rightList.filter(e => !this.rightSelectAccount.includes(e.F_account))
        const leftList = rightList.filter(e => this.rightSelectAccount.includes(e.F_account))
        leftList.forEach(e => {
          if (!this.leftStudentList.find(i => i.F_account === e.F_account)) {
            this.leftStudentList.push(e)
          }
        })
      }
    },
    deleteStudent(idx, row) {
      this.rightStudentList.splice(idx, 1)
    },
    confirmCombine() {
      if (this.selectedStudentList.length === 0) {
        this.$message({
          message: '请先选择学生！',
          type: 'info'
        })
        return
      }
      this.$EleMessageBox.confirm(`您正在操作删除合并账号，请再次确认是否将${this.rightStudentList.length}位学生合并至【${this.student.F_name}】学生账号下。`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '我再想想',
        title: '提示',
        cancelButtonClass: 'combine-cancel-btn',
        confirmButtonClass: 'combine-confirm-btn',
        closeOnClickModal: false,
        closeOnPressEscape: false,
        dangerouslyUseHTMLString: true,
        center: true,
        callback: this.combineStudents
      })
    },
    async combineStudents(action) {
      if (action !== 'confirm') {
        return
      }
      const formData = new FormData()
      formData.append('F_school_id', this.schoolId)
      formData.append('F_student_id', this.student.F_id)
      formData.append('F_delete_student_ids', this.selectedStudentList.map(e => e.F_id).join(','))
      const res = await this.$api.combineStudents(formData)
      if (res.F_responseNo === 10000) {
        this.centerDialogVisible = false
        this.$emit('updateCombination')
        this.$message({
          type: 'success',
          message: '合并成功！'
        })
        return
      } else {
        this.$message({
          type: 'warning',
          message: '合并失败！'
        })
      }
    },
    selectStudent(val) {
      if (val === 1) {
        // close事件的触发时机在nextTick后，所以用nextTick返回promise的回调保证合并时机在close事件后触发
        this.$nextTick().then(() => {
          this.selectedStudentList = this.rightStudentList
        })
      } else {
        this.selectedStudentList = []
      }
      this.selectStudentDialogVisible = false
    },
  }
}
</script>

<style lang="less">
  .combine-cancel-btn, .combine-confirm-btn {
    width: 80px;
  }
</style>

<style lang="less" scoped>
  .tips-select-student {
    margin-bottom: 10px;
    .show-select-student-btn {
      color: #409cff;
      cursor: pointer;
    }
  }
  .select-num {
    margin-bottom: 5px;
    .num {
      color: #409cff;
    }
  }
  .btn {
    &:hover {
      color: #409cff;
    }
  }
  .tips-txt {
    margin: 5px 0;
  }
  .tips-red {
    color: #ff0000;
  }
  .tips-blue {
    color: #409cff;
  }
  :deep(.el-table) {
    .el-table__cell {
      padding: 5px 0;
    }
    .gutter {
      background-color: #ededed;
    }
  }
  .select-student-container {
    display: flex;
    justify-content: space-around;
    align-items: center;
    .unselect-student-container {
      box-sizing: border-box;
      width: calc((100% - 40px) / 2);
      .box {
        border: solid 1px grey;
        margin-top: 5px;
        padding: 10px 10px 0;
        .filter-box {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
          .el-select {
            margin-right: 10px;
          }
        }
        :deep(.el-table) {
          .el-table__cell {
            padding: 5px 0;
          }
          .blue-row {
            color: #409cff;
          }
          .gutter {
            background-color: #ededed;
          }
        }
        .el-pagination {
          display: flex;
          justify-content: center;
          margin: 5px 0;
        }
      }
    }
    .exchange-select-status {
      padding: 0 10px;
      .to-selected, .to-unselect {
        width: 20px;
        height: 30px;
        display: flex;
        justify-content: center;
        align-items: center;
        border: solid 1px rgb(197, 196, 196);
        margin: 5px 0;
        cursor: pointer;
      }
      .selected-status {
        border-color: #409cff;
        color: #409cff;
      }
    }
    .selected-student-container {
      width: calc((100% - 40px) / 2);
      box-sizing: border-box;
      align-self: stretch;
      display: flex;
      flex-direction: column;
      .box {
        flex: 1;
        border: solid 1px grey;
        margin-top: 5px;
        padding: 10px 10px 0;
        :deep(.el-table) {
          .el-table__cell {
            padding: 5px 0;
          }
          .blue-row {
            color: #409cff;
          }
          .gutter {
            background-color: #ededed;
          }
        }
      }
    }
  }
</style>
